'''
Created on Jul 12, 2011

@author: owsuser
'''
import dircache
import commands
from osgeo import gdal
from ESAGSCDA_SPR_Reports.Commons import print_debug
import os.path as spath
'''
gdal_merge.py [-o out_filename] [-of out_format] [-co NAME=VALUE]*
                     [-ps pixelsize_x pixelsize_y] [-tap] [-separate] [-q] [-v] [-pct]
                     [-ul_lr ulx uly lrx lry] [-n nodata_value] [-init "value [value...]"]
                     [-ot datatype] [-createonly] input_files
                     [--help-general]
              '''
debug = False
debug = True

all = '/all'
mask = '/mask'
browse = '/browse'
p_937 = '/937'

def formatAcceptance(file, fr):
    '''checks the format of the file and accepts or rejects the file, 
    depending on settings'''
    accepted = False
    if fr == 1:
        format = ['.jpg']
    if fr == 2:
        format = ['.tif']
    if fr == 3:
        format = ['.tif', '.jpg']
    for f in format:
        if file.endswith(f):   
            accepted = True 
            print_debug(debug, __name__, [file, accepted]),
            break
    return accepted    

def __createName__():
    ''' Creates name for merged image'''
    return 'random_name3.tif'              

def __merge_dir__(f, input_dir, map_dir):
    cmd = 'gdal_merge.py '
    map_dir = '-o ' + map_dir + '/' + __createName__()
    cmd = cmd + map_dir
    list.append(map_dir)
    for i in f:
        if formatAcceptance(i, 1):
            list.append(input_dir + '/' + i)
            cmd = cmd + ' ' + input_dir + '/' + i
    print list 
    print cmd
    print 'start to process'
    print commands.getstatusoutput(cmd)
    
def __get_image_info__(f, input_dir):
    gdalinfo = 'gdalinfo '
    for i in f:
        if formatAcceptance(i, 2):
            cmd_gdalinfo = gdalinfo + input_dir + '/' + i
            print cmd_gdalinfo
            result = commands.getstatusoutput(cmd_gdalinfo)
            n = 1
            for inf in result:
                print n, inf
                n = n + 1
                print '________________'
   
def __georeference_image__(img_path, gcps):
    ''' transforms jpg into geotiff.
    img_path - path to the jpg image
    gcps - sting containing coordinate in format: -gcp pixel line easting 
    northing'''
    gdal_translate = 'gdal_translate '
    gdal_translate = gdal_translate + gcps + ' -of GTiff ' #+ '-ot Float64'
    name = img_path.rstrip('__browse.jpg')
    name = name + '_geo.tif'
    n = 0
    while spath.exists(name):
        n = n + 1
        name = name.split('_geo')
        name = name[0]
        name = name + '_geo_' + n.__str__() + '.tif'
        print_debug(debug, __name__, [name])  
    gdal_translate = gdal_translate + img_path + ' ' + name
    result = commands.getstatusoutput(gdal_translate)
    print_debug(debug, __name__, [result]) 

def georeference(img_set):
    img_path = img_set[0]
    browse = img_set[1]
    mask = img_set[2]
    browse.SetProjection(mask.GetProjection)
    browse.SetGeoTrnsform(mask.GetGeoTransform)
    driver = gdal.GetDriverByName("GTiff")
    driver.create(browse)


def getImageFromDir(path):
    ''' goes to dir, where the browse and the mask are stored opens the files. 
    It returns the list, where the first item is the browse and the second is the mask '''
    img_pair = [None, None, None]
    f = dircache.listdir(path)
    for img in f:
        if formatAcceptance(img, 1):
            img_pair[0] = path + '/' + img
            img_pair[1] = gdal.Open(path + '/' + img)
        if formatAcceptance(img, 2):
            img_pair[2] = gdal.Open(path + '/' + img)
            ds = gdal.Open(path + '/' + img)
    return img_pair
        
def getGCPs(gdal_dataset):
    
    gcps = gdal_dataset.GetGCPs()
    if len(gcps) == 0:
        print_debug(debug, __name__, ['there are no gcps!!!!!']) 
    str_gcp = ''
    for gcp in gcps:
        str_gcp = str_gcp + ' ' + '-gcp ' + ' '
        str_gcp = str_gcp + ' ' + gcp.GCPPixel.__str__() + ' '
        str_gcp = str_gcp + ' ' + gcp.GCPLine.__str__() + ' '
        str_gcp = str_gcp + ' ' + gcp.GCPX.__str__() + ' '
        str_gcp = str_gcp + ' ' + gcp.GCPY.__str__() + ' '
        
    print_debug(debug, __name__, [str_gcp])
    return str_gcp
